var mongoose = require("./setmongoose");

// 检查模型是否已经存在，避免重复定义
var ltcModel;
try {
  ltcModel = mongoose.model("ltc");
} catch (error) {
  var ltcSchema = new mongoose.Schema({
    name: String,
    age: Number,
    sex: String,
    phone: String,
    email: String,
    password: String,
    createdAt: Date,
    updatedAt: Date,
  });
  ltcModel = mongoose.model("ltc", ltcSchema, "ltc");
}

// 检查模型是否已经存在，避免重复定义
var essayModel;
try {
  essayModel = mongoose.model("essay");
} catch (error) {
  var essaySchema = new mongoose.Schema({
    // 文章内容
    context: {
      type: String,
      required: true,
    },

    // 图片数组
    img: [
      {
        type: String,
      },
    ],

    // 话题标签数组
    topic: [
      {
        type: String,
      },
    ],

    // 是否匿名
    anonymity: {
      type: Boolean,
      default: false,
    },

    // 置顶时间（字符串格式，"999"表示不置顶）1
    top_time: {
      type: String,
      default: "999",
    },

    // 评论数
    comments: {
      type: Number,
      default: 0,
    },

    // 点赞用户ID数组
    likes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "zjx", // 用户集合名为zjx
      },
    ],

    // 浏览次数
    views: {
      type: Number,
      default: 0,
    },

    // 标签数组
    tag: [
      {
        type: String,
      },
    ],

    // 作者信息
    author: {
      _id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "zjx", // 用户集合名为zjx
        required: true,
      },
      name: {
        type: String,
        required: true,
      },
      avatar: {
        type: String,
      },
    },

    // 创建时间
    createdata: {
      type: Date,
      default: Date.now,
    },
  });
  essayModel = mongoose.model("essay", essaySchema, "essay");
}

// 检查模型是否已经存在，避免重复定义
var commentsModel;
try {
  commentsModel = mongoose.model("comments");
} catch (error) {
  // 统一的评论模型，支持嵌套回复
  var commentsSchema = new mongoose.Schema({
    content: {
      type: String,
      required: true,
    },
    essayId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "essay",
      required: true,
    },
    author: {
      _id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "ltc",
        required: true,
      },
      name: {
        type: String,
        required: true,
      },
    },
    createdata: {
      type: Date,
      default: Date.now,
    },
    like: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "ltc",
      default: [],
    },
    parentId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "comments",
      default: null,
    },
    replyTo: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "ltc",
      default: null,
    },
  });
  commentsModel = mongoose.model("comments", commentsSchema, "comments");
}

module.exports = { ltcModel, essayModel, commentsModel };
